package com.sukumar.android.backit.activity;

import java.util.regex.Pattern;

import android.content.ContentValues;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.widget.Toast;

import com.sukumar.android.backit.R;
import com.sukumar.android.backit.db.BackItDBData.BackItRule;

public class BackItRulePreferenceActivity extends PreferenceActivity {

	private String oldPattern = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.rule_preference);
		Preference usagePref = (Preference) findPreference(getText(R.string.rule_save_key));
		SharedPreferences sharedpref = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		EditTextPreference repeats = (EditTextPreference) findPreference(getText(R.string.rule_repeat_key));

		if (sharedpref != null
				&& sharedpref.getString(
						getText(R.string.pattern_key).toString(), "").equals(
						"BING")) {
			EditTextPreference name = (EditTextPreference) findPreference(getText(R.string.rule_name_key));
			EditTextPreference pattern = (EditTextPreference) findPreference(getText(R.string.pattern_key));
			CheckBoxPreference vibrate = (CheckBoxPreference) findPreference(getText(R.string.vibration_key));
			CheckBoxPreference enabled = (CheckBoxPreference) findPreference(getText(R.string.rule_enabled_key));

			oldPattern = sharedpref.getString(getText(R.string.pattern_key)
					.toString(), "");
			name.setEnabled(false);
			pattern.setEnabled(false);
			vibrate.setEnabled(false);
			enabled.setEnabled(false);
			repeats.setEnabled(false);
		} else {
			oldPattern = sharedpref.getString(getText(R.string.pattern_key)
					.toString(), "");
		}
		usagePref
				.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

					@Override
					public boolean onPreferenceClick(Preference paramPreference) {
						SharedPreferences sharedpref = PreferenceManager
								.getDefaultSharedPreferences(getApplicationContext());
						int duration = getDuration(sharedpref.getString(
								getText(R.string.rule_repeat_key).toString(),
								""));
						if (duration != -999) {
							if (validateFields()) {
								saveRule(sharedpref, duration);
								deletePref(sharedpref);
								finish();
								onDestroy();
								return true;
							} else {
								Toast.makeText(
										getApplicationContext(),
										"Rule name and SMS search text are mandatory.",
										Toast.LENGTH_LONG).show();
								return false;
							}
						} else {
							Toast.makeText(
									getApplicationContext(),
									"Time format is incorrect, please enter in \'mm:ss\' format. ex: 1:5, 0:10, 15:30",
									Toast.LENGTH_LONG).show();
							return false;
						}
					}
				});

		repeats.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

			@Override
			public boolean onPreferenceChange(Preference preference,
					Object newValue) {

				int duration = getDuration(newValue.toString());
				if (duration == -999) {
					Toast.makeText(
							getApplicationContext(),
							"Time format is incorrect, please enter in \'mm:ss\' format. ex: 1:5, 0:10, 15:30",
							Toast.LENGTH_LONG).show();
					return false;
				} else {
					return true;
				}
			}
		});
	}

	private void saveRule(SharedPreferences pSharedPref, int duration) {
		Cursor c = null;
		int ruleId = -999;
		try {
			c = getContentResolver().query(BackItRule.CONTENT_URI,
					new String[] { BackItRule._ID },
					BackItRule.PATTERN + " = ?", new String[] { oldPattern },
					null);
			if (c != null) {
				if (c.getCount() > 0) {
					c.moveToFirst();
					ruleId = c.getInt(0);
				}
			}
		} catch (Exception e) {

		} finally {
			c.close();
		}

		if (ruleId == -999) {
			ContentValues values = new ContentValues();
			values.put(BackItRule.RULENAME, pSharedPref.getString(
					getText(R.string.rule_name_key).toString(), ""));
			values.put(BackItRule.PATTERN, pSharedPref.getString(
					getText(R.string.pattern_key).toString(), ""));
			values.put(BackItRule.NOTIFURI, pSharedPref.getString(
					getText(R.string.rule_rt_key).toString(), ""));
			values.put(BackItRule.VIBRATE, (pSharedPref.getBoolean(
					getText(R.string.vibration_key).toString(), true) ? "Y"
					: "N"));
			values.put(BackItRule.ENABLED, (pSharedPref.getBoolean(
					getText(R.string.rule_enabled_key).toString(), true) ? "Y"
					: "N"));
			values.put(BackItRule.REPEAT, duration);

			getContentResolver().insert(BackItRule.CONTENT_URI, values);

		} else {
			if (oldPattern.equals("BING")) {
				ContentValues values = new ContentValues();
				values.put(BackItRule.NOTIFURI, pSharedPref.getString(
						getText(R.string.rule_rt_key).toString(), ""));
				getContentResolver().update(BackItRule.CONTENT_URI, values,
						BackItRule._ID + " = ?", new String[] { ruleId + "" });
			} else {
				ContentValues values = new ContentValues();
				values.put(BackItRule.RULENAME, pSharedPref.getString(
						getText(R.string.rule_name_key).toString(), ""));
				values.put(BackItRule.PATTERN, pSharedPref.getString(
						getText(R.string.pattern_key).toString(), ""));
				values.put(BackItRule.NOTIFURI, pSharedPref.getString(
						getText(R.string.rule_rt_key).toString(), ""));
				values.put(BackItRule.VIBRATE, (pSharedPref.getBoolean(
						getText(R.string.vibration_key).toString(), true) ? "Y"
						: "N"));
				values.put(BackItRule.ENABLED,
						(pSharedPref.getBoolean(
								getText(R.string.rule_enabled_key).toString(),
								true) ? "Y" : "N"));
				values.put(BackItRule.REPEAT, duration);

				getContentResolver().update(BackItRule.CONTENT_URI, values,
						BackItRule._ID + " = ?", new String[] { ruleId + "" });
			}
		}

	}

	@Override
	protected void onDestroy() {
		SharedPreferences sharedpref = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		deletePref(sharedpref);
		super.onDestroy();
	}

	private void deletePref(SharedPreferences sharedpref) {
		Editor spEdi = sharedpref.edit();
		spEdi.remove(getText(R.string.rule_name_key).toString());
		spEdi.remove(getText(R.string.pattern_key).toString());
		spEdi.remove(getText(R.string.rule_rt_key).toString());
		spEdi.remove(getText(R.string.vibration_key).toString());
		spEdi.remove(getText(R.string.rule_enabled_key).toString());
		spEdi.remove(getText(R.string.rule_repeat_key).toString());
		spEdi.commit();
	}

	private int getDuration(String strDuration) {
		int duration = -999;
		Pattern TIME_PATTERN = Pattern.compile("[0-5]?[0-9]:[0-5]?[0-9]");
		Pattern SPLIT_PATTERN = Pattern.compile(":");
		if (strDuration.equals("") || strDuration.equals("mm:ss")) {
			duration = -99;
		} else if (TIME_PATTERN.matcher(strDuration).matches()) {
			String time[] = SPLIT_PATTERN.split(strDuration);
			if (time.length == 2) {
				int min = Integer.parseInt(time[0]);
				int sec = Integer.parseInt(time[1]);
				duration = (min * 60) + sec;
			}
		}
		return duration;
	}

	private boolean validateFields() {
		boolean valid = false;
		EditTextPreference name = (EditTextPreference) findPreference(getText(R.string.rule_name_key));
		EditTextPreference pattern = (EditTextPreference) findPreference(getText(R.string.pattern_key));
		if (name.getText() != null && !name.getText().equals("") && pattern.getText() != null && !pattern.getText().equals("")) {
			valid = true;
		}

		return valid;
	}

}
